/**
 * 数据表格的工具,主要是封装一些常用的设置。
 */
var BsGridUtil = function () {

    //给组件增加默认参数列表
    var treeGridDefaults = {
        locale:"zh-CN",
        gridId:"#treeGridId",
        rootParentId:1,
        url: null,
        method:"post",
        toolbar: '#tb',
        striped: true,
        sidePagination: 'server',
        idField: 'id',
        parentIdField: 'pid',
        treeShowField: 'name',
        selectItemName: 'btSelectItem',
        singleSelect: true,
        clickToSelect:true,
        showRefresh: true,
        initBtnEvent:true,
        treeVerticalcls: 'vertical',
        treeVerticalLastcls: 'vertical last',
        treeSpacecls: 'space',
        treeNodecls: 'node',
        treeCellcls: 'treenode',
        treeTextcls: 'text',
        buttonsClass: 'primary',
        initialState: "expanded",//默认是展开 收縮collapsed
        treeColumn: null,//伸缩图标显示在哪行
        searchForm: '#queryForm',
        searchFormSubmitBtn: '#searchFormSubmitBtn',
        searchFormResetBtn: '#searchFormResetBtn',
        contentType : "application/x-www-form-urlencoded",
        onLoadSuccess:function () {
        }
    };

    function initBsTreeGrid(op) {
        var options = $.extend(true, {}, treeGridDefaults, op);
        setOnLoadSuccess(options);
        var $treeGrid = $(options.gridId).bootstrapTable(options);

        if (options.initBtnEvent) {
            $('#refreshBtn,.refreshBtn').on('click', function () {
                $treeGrid.bootstrapTable('refresh',{url:options.url});
            })

            //绑定提交按钮
            $(options.searchFormSubmitBtn).click(function () {
                if ($(options.searchForm).validate().form()) {
                    var data = FormUtils.getFormObj(options.searchForm);
                    var opt = {
                        url: options.url,
                        silent: true,
                        query:data
                    };
                    $treeGrid.bootstrapTable('refresh', opt);
                }
                return false;
            });

            //绑定清除按钮
            $(options.searchFormResetBtn).click(function () {
                FormUtils.clearForm(options.searchForm);
                $treeGrid.bootstrapTable("refresh",{url:options.url});
                return false;
            });
        }
        return $treeGrid;

    }

    var dataGridDefaults = {
        gridId: "#grid-data",
        classes:'table table-bordered table-hover',
        locale:"zh-CN",
        height: undefined,
        undefinedText: '-',
        sortName: "",//排序字段
        sortOrder: '',//desc asc
        idField: "id",//指示哪个字段是标识字段
        uniqueId: "",//唯一标识
        sortStable: true,
        striped: true,
        cache: false,
        onlyInfoPagination: false,
        pagination: true,
        searchOnEnterKey: false,
        search: false,
        strictSearch: true,
        showExport: true,
        showHeader: true,
        showFooter: false,
        showColumns: true,
        showFullscreen:true,
        showToggle: true,
        showRefresh: true,
        autoRefresh:true,
        showJumpto: true,
        smartDisplay: false,
        escape: false,
        cardView: false,
        detailView: false,
        showPaginationSwitch:true,
        trimOnSearch: false,
        checkboxHeader: true,
        sortable: true,
        silentSort: true,
        maintainSelected: false,
        singleSelect: true,
        clickToSelect:true,
        initBtnEvent:true,
        exportDataType:"all",
        buttonsAlign: 'right',
        columns: [],
        data: [],
        dataField: 'rows',
        method: 'post',
        url: undefined,
        ajax: undefined,
        contentType : "application/x-www-form-urlencoded",
        dataType: 'json',
        ajaxOptions: {},
        queryParams: queryParams,
        queryParamsType: 'limit', // undefined (这里是根据不同的参数，选择不同的查询的条件)
        sidePagination: 'server', //  or server
        pageNumber: 1,
        pageSize: 10,
        pageList: [10,20,30,50,100],
        paginationHAlign: 'right', //right, left
        paginationVAlign: 'bottom', //bottom, top, both
        paginationDetailHAlign: 'left', //right, left
        paginationPreText: '&lsaquo;',
        paginationNextText: '&rsaquo;',
        searchTimeOut: 500,
        searchText: undefined,
        searchAlign: 'right',
        selectItemName: 'btSelectItem',
        minimumCountColumns: 1,
        detailFormatter: function (index, row) {
            return '';
        },
        toolbarAlign: 'left',
        toolbar: '#tb',
        buttonsToolbar:"",
        buttonsClass: 'primary',
        iconsPrefix: 'fa', // glyphicon of fa (font awesome)
        icons: {
            paginationSwitchDown: 'fa-caret-square-o-down',
            paginationSwitchUp: 'fa-caret-square-o-up',
            refresh: 'fa-refresh',
            toggleOff: 'fa-toggle-off',
            toggleOn: 'fa-toggle-on',
            columns: 'fa-th-list',
            fullscreen: 'fa-arrows-alt',
            detailOpen: 'fa-plus',
            detailClose: 'fa-minus',
            autoRefresh:"fa-clock"
        },
        iconSize: undefined,
        customSearch: $.noop,
        customSort: $.noop,
        searchForm: '#queryForm',
        searchFormSubmitBtn: '#searchFormSubmitBtn',
        searchFormResetBtn: '#searchFormResetBtn',
        responseHandler: function (data) {
            if (data) {
                data = data.data;
                var newData = {};
                newData.total = data.totalCount;
                newData.rows = data.list;
                return newData;
            } else {
                console.error("没有分页数据")
            }
        },
        rowStyle: function (row, index) {
            return {};
        },

        rowAttributes: function (row, index) {
            return {};
        },

        footerStyle: function (row, index) {
            return {};
        },

        onAll: function (name, args) {
            return false;
        },
        onClickCell: function (field, value, row, $element) {
            return false;
        },
        onDblClickCell: function (field, value, row, $element) {
            return false;
        },
        onClickRow: function (item, $element) {
            return false;
        },
        onDblClickRow: function (item, $element) {
            return false;
        },
        onSort: function (name, order) {
            return false;
        },
        onCheck: function (row) {
            return false;
        },
        onUncheck: function (row) {
            return false;
        },
        onCheckAll: function (rows) {
            return false;
        },
        onUncheckAll: function (rows) {
            return false;
        },
        onCheckSome: function (rows) {
            return false;
        },
        onUncheckSome: function (rows) {
            return false;
        },
        onLoadSuccess: function (data) {
            return false;
        },
        onLoadError: function (status) {
            return false;
        },
        onColumnSwitch: function (field, checked) {
            return false;
        },
        onPageChange: function (number, size) {
            return false;
        },
        onSearch: function (text) {
            return false;
        },
        onToggle: function (cardView) {
            return false;
        },
        onPreBody: function (data) {
            return false;
        },
        onPostBody: function () {
            return false;
        },
        onPostHeader: function () {
            return false;
        },
        onExpandRow: function (index, row, $detail) {
            return false;
        },
        onCollapseRow: function (index, row) {
            return false;
        },
        onRefreshOptions: function (options) {
            return false;
        },
        onRefresh: function (params) {
            return false;
        },
        onPageGo: function (event) {
            return false;
        },
        onResetView: function () {
            return false;
        },
        formatJumpto: function () {
            return '跳转';
        }
    };

    /**
     * 查询参数封装
     * @param params
     * @returns {{pageSize: *, pageNo: *, offset: *, search: *, sortBy: string}}
     */
    function queryParams(params) {
        //这里的键的名字和控制器的变量名必须一直，这边改动，控制器也需要改成一样的
        var defaultParam = {
            pageSize:params.limit,//页面大小
            pageNo: params.pageNo ,//页码
            offset: params.offset,//第x页
            sortBy:toLowerLine(params.sort) + " "  + params.order//排序列名
        };
        //如果配置为true，开启关键字搜索
        if (params.search){
            $.extend(true,defaultParam,{keyWord:params.searchText})
        }
        return defaultParam;
    }

    /**
     * 驼峰转换下划线
     * @param str
     * @returns {*}
     */
    function toLowerLine(str) {
        if (str){
            var temp = str.replace(/[A-Z]/g, function (match) {
                return "_" + match.toLowerCase();
            });
            if(temp.slice(0,1) === '_'){ //如果首字母是大写，执行replace时会多一个_，这里需要去掉
                temp = temp.slice(1);
            }
            return temp;
        }
        return "";
    };

    /**
     * 下划线转驼峰
     * @param str
     * @returns {*}
     */
    function toCamel(str) {
        if (str){
            return str.replace(/([^_])(?:_+([^_]))/g, function ($0, $1, $2) {
                return $1 + $2.toUpperCase();
            });
        }
        return "";
    }

    /**
     * 统一加上onLoadSuccess方法。
     * @param op
     */
    function setOnLoadSuccess(op) {
        if ($.isFunction(op.onLoadSuccess)) {
            //如果已经设置了加载完成事件,则需要重新封装。
            var originFun = op.onLoadSuccess;
            var newFun = function (data) {
                if (op.treeShowField) {
                    data = $(op.gridId).treegrid(op);
                } else {
                    data = $(op.gridId).treegrid(op);
                }
                originFun(data);
            };
            op.onLoadSuccess = newFun;
        }
    }

    /**
     * 初始化数据表格
     * @param op
     * @returns {jQuery}
     */
    function initBsGrid(op) {
        var options = $.extend(true, {}, dataGridDefaults, op);
        var $bsGrid = $(options.gridId).bootstrapTable(options);
        if (options.initBtnEvent) {

            //绑定提交按钮
            $(options.searchFormSubmitBtn).click(function () {
                if ($(options.searchForm).validate().form()) {
                    var data = FormUtils.getFormObj(options.searchForm);
                    $bsGrid.bootstrapTable('refresh', {query:data});
                }
                return false;
            });

            //绑定清除按钮
            $(options.searchFormResetBtn).click(function () {
                FormUtils.clearForm(options.searchForm);
                $bsGrid.bootstrapTable("refresh",{url:options.url});
                return false;
            });
        }
        return $bsGrid;
    }

    var listGridDefaults = {
        gridId: "#grid-data",
        locale:"zh-CN",
        classes:'table table-bordered table-hover',
        undefinedText: '-',
        sortName: '',
        sortOrder: '',//desc asc
        sortable: true,
        silentSort: true,
        sortStable: true,
        striped: true,
        showRefresh: true,
        columns: [],
        data: [],
        dataField: 'rows',
        method: 'post',
        initBtnEvent:true,
        url: undefined,
        ajax: undefined,
        cache: false,
        contentType : "application/x-www-form-urlencoded",
        dataType: 'json',
        ajaxOptions: {},
        queryParams: queryParams,
        queryParamsType: 'limit', // undefined (这里是根据不同的参数，选择不同的查询的条件)
        onlyInfoPagination: false,
        sidePagination: 'server', //  or server
        totalRows: 0, // server side need to set
        pagination: true,
        pageNumber: 1,
        pageSize: 10,
        pageList: [10,20,30,50,100],
        paginationHAlign: 'right', //right, left
        paginationVAlign: 'bottom', //bottom, top, both
        paginationDetailHAlign: 'left', //right, left
        paginationPreText: '&lsaquo;',
        paginationNextText: '&rsaquo;',
        searchTimeOut: 500,
        searchText: undefined,
        searchOnEnterKey: false,
        strictSearch: false,
        searchAlign: 'right',
        selectItemName: 'btSelectItem',
        exportDataType:"all",
        showFooter: false,
        buttonsAlign: 'right',
        smartDisplay: false,
        escape: false,
        minimumCountColumns: 1,
        idField: "id",
        uniqueId: "",
        detailFormatter: function (index, row) {
            return '';
        },
        showJumpto: true,
        showPaginationSwitch:false,
        trimOnSearch: true,
        clickToSelect: true,
        singleSelect: true,
        toolbarAlign: 'left',
        checkboxHeader: true,
        maintainSelected: false,
        iconSize: undefined,
        toolbar: '#tb',
        buttonsToolbar:"btb",
        searchForm: '#queryForm',
        searchFormSubmitBtn: '#searchFormSubmitBtn',
        searchFormResetBtn: '#searchFormResetBtn',
        buttonsClass: 'primary',
        iconsPrefix: 'fa', // glyphicon of fa (font awesome)
        icons: {
            paginationSwitchDown: 'fa-caret-square-o-down',
            paginationSwitchUp: 'fa-caret-square-o-up',
            refresh: 'fa-refresh',
            toggleOff: 'fa-toggle-off',
            toggleOn: 'fa-toggle-on',
            columns: 'fa-th-list',
            fullscreen: 'fa-arrows-alt',
            detailOpen: 'fa-plus',
            detailClose: 'fa-minus',
            autoRefresh:"fa-clock"
        },
        customSearch: $.noop,
        customSort: $.noop,
        columns: [[
            {field: 'id',title:'Id',visible:false},
            {field: 'name', title: '名称', visible: true, sortable: true}
        ]],
        formatJumpto: function () {
            return '跳转';
        },
        responseHandler: function (data) {
            if (data) {
                if (data) {
                    var newData = {};
                    newData.total = data.length;
                    newData.rows = data;
                    return newData;
                }
            } else {
                console.error("没有分页数据")
            }
        },
    };

    /**
     * 初始化列表样式的grid(没有分页)
     * @param op
     * @returns {jQuery}
     */
    function initListGrid(op) {
        var options = $.extend({}, listGridDefaults, op);
        var $dataGrid = $(options.gridId).bootstrapTable(options);
        if (options.initBtnEvent) {

            //绑定提交按钮
            $(options.searchFormSubmitBtn).click(function () {
                if ($(options.searchForm).validate().form()) {
                    var data = FormUtils.getFormObj(options.searchForm);
                    $dataGrid.bootstrapTable('refresh', {query:data});
                }
                return false;
            });

            //绑定清除按钮
            $(options.searchFormResetBtn).click(function () {
                FormUtils.clearForm(options.searchForm);
                $dataGrid.bootstrapTable("refresh",{url:options.url});
                return false;
            });
        }
        return $dataGrid;
    }

    return {
        initBsTreeGrid: initBsTreeGrid,
        initBsGrid: initBsGrid,
        initListGrid: initListGrid
    }
}();